﻿using System;
using System.Collections.Generic;
using System.Web;
using SystemModel;

public class BasePage : System.Web.UI.Page
{
    protected string FullPath;//当前页面的全路径    
    protected string LastPath;//请求连接到此页面的页面路径    
    protected string AppPhysisPath;//当前应用程序(虚拟目录)物理路径    
    protected string AppPath;//当前应用程序(虚拟目录)虚拟路径    
    protected string UserHostAddress;//连接用户地址
    protected string LangName; //语言
    protected string aspxVirtualPath;//aspnet虚拟地址名称
    protected string aspVirtualPath;//asp虚拟地址名称
    protected string UpLoadPath;//上传路径

    public BasePage()
        : base()
    {
        FullPath = Context.Request.Url.ToString();
        LastPath = Context.Request.UrlReferrer != null ? Context.Request.UrlReferrer.ToString() : string.Empty;
        AppPhysisPath = Context.Server.MapPath("~");
        AppPath = Context.Request.IsSecureConnection ? "https://" : "http://";
        AppPath += Context.Request.Url.Host;
        AppPath += Context.Request.Url.IsDefaultPort ? "" : ":" + Context.Request.Url.Port.ToString();
        AppPath += Context.Request.ApplicationPath;
        UserHostAddress = Context.Request.UserHostAddress;
        aspVirtualPath = System.Configuration.ConfigurationManager.AppSettings["aspVirtualPath"];
        aspxVirtualPath = System.Configuration.ConfigurationManager.AppSettings["aspxVirtualPath"];
        UpLoadPath = aspxVirtualPath == "" ? "/UpLoad/" : "/" + aspxVirtualPath + "/UpLoad/";
    }

    /// <summary>
    /// 重写加载事件
    /// </summary>
    /// <param name="e"></param>
    protected override void OnLoad(EventArgs e)
    {
        if (CurrentSession == null)
        {
            Response.Redirect("~/System/Message/Timeout.aspx");
        }

        base.OnLoad(e);
    }

    #region Cookies操作
    /// <summary>
    /// Cookies：赋值
    /// </summary>
    /// <param name="strKey">主键</param>
    /// <param name="strValue">键值</param>
    /// <param name="strDay">有效天数</param>
    /// <returns>操作是否成功</returns>
    public bool setCookie(string strKey, string strValue, int strDay)
    {
        try
        {
            HttpCookie Cookie = new HttpCookie(strKey);
            //当需要跨域名访问时,给cookie指定域名即可,格式为.xxx.com
            //Cookie.Domain = ".xxx.com";
            Cookie.Expires = DateTime.Now.AddDays(strDay);
            Cookie.Value = strValue;
            System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
            return true;
        }
        catch
        {
            return false;
        }
    }


    /// <summary>
    /// Cookies：读取
    /// </summary>
    /// <param name="strKey">主键</param>
    /// <returns>键所对应的值</returns>
    public string getCookie(string strKey)
    {
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[strKey];
        if (Cookie != null)
        {
            return Cookie.Value.ToString();
        }
        else
        {
            return null;
        }
    }

    /// <summary>
    /// Cookies：删除
    /// </summary>
    /// <param name="strName">主键</param>
    /// <returns>操作是否成功</returns>
    public bool delCookie(string strName)
    {
        try
        {
            HttpCookie Cookie = new HttpCookie(strName);
            //当需要跨域名访问时,给cookie指定域名即可,格式为.xxx.com
            //Cookie.Domain = ".xxx.com";
            Cookie.Expires = DateTime.Now.AddDays(-1);
            System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
            return true;
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region URL参数解析
    /// <summary>
    /// URL参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <returns>值(INT型)</returns>
    protected int ParseQueryInt(string name)
    {
        int i;
        if (Request.QueryString[name] == null)
        {
            throw new ArgumentException("Can not find parameter:'" + name + "'");
        }
        try
        {
            i = int.Parse(Request.QueryString[name]);
        }
        catch
        {
            throw new ArgumentException("parameter:'" + name + "' value error!");
        }
        return i;
    }

    /// <summary>
    /// URL参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <param name="num">默认值</param>
    /// <returns>值(INT型)</returns>
    protected int ParseQueryInt(string name,int num)
    {
        int i = 0;
        if (Request.QueryString[name] == null)
        {
            //throw new ArgumentException("Can not find parameter:'" + name + "'");
            i = num;
        }
        try
        {
            i = int.Parse(Request.QueryString[name]);
        }
        catch
        {
            //throw new ArgumentException("parameter:'" + name + "' value error!");
            i = num;
        }
        return i;
    }

    /// <summary>
    /// URL参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <returns>值(STRING型)</returns>
    protected string ParseQueryString(string name)
    {
        string s;

        if (Request.QueryString[name] == null)
        {
            throw new ArgumentException("Can not find parameter:'" + name + "'");
        }

        s = Request.QueryString[name];
        return s;
    }

    /// <summary>
    /// URL参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <param name="str">默认值</param>
    /// <returns>值(STRING型)</returns>
    protected string ParseQueryString(string name,string str)
    {
        string s;

        if (Request.QueryString[name] == null)
        {
            //throw new ArgumentException("Can not find parameter:'" + name + "'");
            s = str;
        }

        s = Request.QueryString[name];
        return s;
    }

    /// <summary>
    /// URL参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <returns>值(INT型数组)</returns>
    protected int[] ParseQueryStringIntArray(string name)
    {
        if (Request.QueryString[name] == null)
        {
            throw new ArgumentException("Can not find parameter:'" + name + "'");
        }
        string[] strArr = Request.QueryString.GetValues(name);
        int[] iArr = new int[strArr.Length];
        try
        {
            for (int loop = 0; loop < strArr.Length; loop++)
            {
                iArr[loop] = int.Parse(strArr[loop]);
            }
        }
        catch
        {
            throw new ArgumentException("parameter:'" + name + "' value error!");
        }
        return iArr;
    }

    /// <summary>
    /// URL参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <returns>值(STRING型数组)</returns>
    protected string[] ParseQueryStringStringArray(string name)
    {
        if (Request.QueryString[name] == null)
        {
            throw new ArgumentException("Can not find parameter:'" + name + "'");
        }
        string[] strArr = Request.QueryString.GetValues(name);
        return strArr;
    }
    #endregion

    #region FORM参数解析
    /// <summary>
    /// FORM参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <returns>值(INT型)</returns>
    protected int ParseFormInt(string name)
    {
        int i;
        if (Request.Form[name] == null)
        {
            throw new ArgumentException("找不到参数:" + name);
        }
        try
        {
            i = int.Parse(Request.Form[name]);
        }
        catch
        {
            throw new ArgumentException("参数:" + name + "值错误");
        }
        return i;
    }

    /// <summary>
    /// FORM参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <returns>值(STRING型)</returns>
    protected string ParseFormString(string name)
    {
        string s;
        if (Request.Form[name] == null)
        {
            throw new ArgumentException("找不到参数:" + name);
        }
        s = Request.Form[name];
        return s;
    }

    /// <summary>
    /// FORM参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <returns>值(INT型数组)</returns>
    protected int[] ParseFormIntArray(string name)
    {
        if (Request.Form[name] == null)
        {
            throw new ArgumentException("找不到参数:" + name);
        }
        string[] strArr = Request.Form.GetValues(name);
        int[] iArr = new int[strArr.Length];
        try
        {
            for (int loop = 0; loop < strArr.Length; loop++)
            {
                iArr[loop] = int.Parse(strArr[loop]);
            }
        }
        catch
        {
            throw new ArgumentException("参数:" + name + "值错误");
        }
        return iArr;
    }

    /// <summary>
    /// FORM参数解析
    /// </summary>
    /// <param name="name">参数名称</param>
    /// <returns>值(STRING型数组)</returns>
    protected string[] ParseFormStringArray(string name)
    {
        if (Request.Form[name] == null)
        {
            throw new ArgumentException("找不到参数:" + name);
        }
        string[] strArr = Request.Form.GetValues(name);
        return strArr;
    }
    #endregion

    #region 页面跳转
    /// <summary>
    /// 页面操作成功后跳转(返回原页面)
    /// </summary>
    /// <param name="message">跳转后的页面显示的信息</param>
    protected void Direct(string message)
    {
        string info = Server.UrlEncode(message);
        string path = Server.UrlEncode(FullPath);
        Response.Redirect("~/System/Message/Success.aspx?info=" + info + "&path=" + path, false);
    }

    /// <summary>
    /// 页面操作成功后跳转(返回另一个页面)
    /// </summary>
    /// <param name="message">跳转后的页面显示的信息</param>
    /// <param name="returnPath">新的页面路径</param>
    protected void Direct(string message, string returnPath)
    {
        string info = Server.UrlEncode(message);
        string path = Server.UrlEncode(this.ResolveUrl(returnPath));
        Response.Redirect("~/System/Message/Success.aspx?info=" + info + "&path=" + path, false);
    }

    /// <summary>
    /// 页面出错时的通用处理
    /// </summary>
    /// <param name="e"></param>
    protected override void OnError(EventArgs e)
    {
        /*
        try
        {
            //处理页面抛出的没有处理的错误
            Exception lastError = Server.GetLastError().GetBaseException();//获取异常
            string errMessage = lastError.Message;//异常内容
            string path = FullPath;//页面全路径
            Server.ClearError();
            string redirectUrl = string.Format("~/System/Message/Err.aspx?path={0}&err={1}", Server.UrlEncode(path), Server.UrlEncode(errMessage));
            Response.Expires = -1;
            Response.Redirect(redirectUrl, true);
            base.OnError(e);
        }
        catch (Exception)
        {

        }*/
        base.OnError(e);
    }
    #endregion

    #region 系统session
    /// <summary>
    /// 获取保存用户信息的Session
    /// </summary>
    protected UserSession CurrentSession
    {
        get
        {
            return (UserSession)Session["LoginUser"];
        }
        set
        {
            Session["LoginUser"] = value;
        }
    }

    /// <summary>
    /// 是否登录
    /// </summary>
    protected bool isLogin
    {
        get
        {
            return Session["LoginUser"] != null;
        }
    }

    /// <summary>
    /// 退出登录
    /// </summary>
    protected void Logout()
    {
        Session["LoginUser"] = null;
    }

    #endregion

    #region 用户权限
    /// <summary>
    /// 获取用户权限
    /// </summary>
    /// <param name="ModuleCode">页面编码</param>
    /// <returns></returns>
    public void CheckUserPermission(string ModuleCode)
    {
        if (CurrentSession.UserID == 1)
        {
            //系统管理员
            return;
        }

        if (!CurrentSession.UserMenu.ContainsKey(ModuleCode))
        {
            //没权限访问
            Response.Redirect("~/System/Message/NoPermission.htm");
        }
    }
    #endregion

    #region 格式化时间
    /// <summary>
    /// 格式化时间
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string SetShortDateTime(string str)
    {
        string reString = "";
        try
        {
            DateTime date = Convert.ToDateTime(str);
            reString = date.ToString("yyyy-MM-dd");
        }
        catch (Exception ex)
        {
            //throw ex;
        }
        return reString;
    }
    #endregion

    #region JS方法
    /// <summary>
    /// 消息提示框
    /// </summary>
    /// <param name="Msg">提示内容</param>
    public void Alert(string Msg)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "系统提示", "alert('" + Msg + "')", true);
    }

    /// <summary>
    /// 消息提示框
    /// </summary>
    /// <param name="Title">标题</param>
    /// <param name="Msg">提示内容</param>
    public void Alert(string Title, string Msg)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), Title, "alert('" + Msg + "')", true);
    }

    /// <summary>
    /// 消息提示并刷新页面
    /// </summary>
    /// <param name="Msg"></param>
    /// <param name="url"></param>
    public void Redirect(string Msg)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "系统提示", "alert('" + Msg + "');window.location.href=window.location.href", true);
    }

    /// <summary>
    /// 消息提示并重定向新的url
    /// </summary>
    /// <param name="Msg">提示内容</param>
    /// <param name="url">url</param>
    public void Redirect(string Msg, string Url)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "系统提示", "alert('" + Msg + "');window.location.href='" + Url + "'", true);
    }

    /// <summary>
    /// 消息提示并重定向新的url
    /// </summary>
    /// <param name="Title">标题</param>
    /// <param name="Msg">提示内容</param>
    /// <param name="url">url</param>
    public void Redirect(string Title,string Msg, string Url)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "系统提示", "alert('" + Msg + "');window.location.href='" + Url + "'", true);
    }
    #endregion

    #region 文本工具类（用于处理一些文本的转换等）
    /// <summary>
    /// 用于防止简单的查询时的SQL注入
    /// </summary>
    /// <param name="oldStr">原始文本</param>
    /// <returns>替换后的文本</returns>
    public static string ReplaceText(string oldStr)
    {
        //需要被替换的字符
        string[] str_illegal = new string[] { "'" };
        //替换后的字符(索引对应)
        string[] str_legitimate = new string[] { "" };

        string newStr = "";

        for (int i = 0; i < str_illegal.Length; i++)
        {
            newStr = oldStr.Replace(str_illegal[i], str_legitimate[i]);
        }

        return newStr;
    }
    #endregion

}

